package com.bite.book.interceptor;

import com.bite.book.constant.Constants;
import com.bite.book.mode.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
@Slf4j
@Component
//定义一个拦截器；
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      log.info("preHandle:目标方法执行前");
      //true:执行；false:拦截；
        HttpSession session= request.getSession(false);
        //参数校验；
        //返回数据；

        if(!checkUser(session)){
            response.setContentType("text/html;charset=utf-8");
            response.setStatus(401);
            String msg="用户没有登录";
            response.getOutputStream().write(msg.getBytes("UTF-8"));
            return false;
        }
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("postHandler:目标方法完成之后");
    }
     public boolean checkUser(HttpSession session){
         if(session==null|| session.getAttribute(Constants.SESSION_USER_KEY)==null){
             log.warn("用户没有登录");
             return false;
         }
         UserInfo userInfo=(UserInfo)session.getAttribute(Constants.SESSION_USER_KEY);
         if(userInfo==null||userInfo.getId()<=0){
             return false;
         }
         log.info("用户登录成功");
         return true;

     }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("afterCompletion:图形渲染完成之后");
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
